import 'dart:convert';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/api/odoo/dms_file_odoo_api.dart';
import 'package:flutter_admin/api/odoo/purchase_qualifications_file_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/dms_file.dart';
import 'package:flutter_admin/models/odoo/purchase_qualifications_file.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/loading_dialog.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class PurchaseQualificationsFileUpload extends StatefulWidget {

  final String? suppliercode;

  PurchaseQualificationsFileUpload({Key? key,required this.suppliercode}):super(key: key);

  @override
  _PurchaseQualificationsFileUploadState createState() => _PurchaseQualificationsFileUploadState();
}

class _PurchaseQualificationsFileUploadState extends State<PurchaseQualificationsFileUpload> {
  PurchaseQualificationsFile purchaseQualificationsFile = PurchaseQualificationsFile();

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  DateFormat format= DateFormat('yyyy-MM-dd');
  @override
  void initState() {
    purchaseQualificationsFile.suppliercode = widget.suppliercode;
    purchaseQualificationsFile.directoryId = "634";
    super.initState();
  }

  _upload() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom, allowedExtensions: ['pdf'], withData: true);

    if (result == null) {
      return;
    }
    // if (result.files.first.size > 1048 * 1048 * 20) {
    //   cryAlert(context, S.of(context).sizeLimit);
    //   return;
    // }
    formKey.currentState!.save();
    purchaseQualificationsFile.content = base64Encode(result.files.first.bytes!);
    setState(() {
      purchaseQualificationsFile.filename = result.files.first.name;
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            label: '企业资质文件',
            value: purchaseQualificationsFile.qualificationsname,
            onSaved: (v) {
              purchaseQualificationsFile.qualificationsname = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInput(
            label: '发证机构',
            value: purchaseQualificationsFile.issuingauthority,
            onSaved: (v) {
              purchaseQualificationsFile.issuingauthority = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelectDate(
            context,
            label: '发证日期',
            lastDate: isNotBlank(purchaseQualificationsFile.expirydate)
                 ? format.parse(purchaseQualificationsFile.expirydate!)
                 : null,
            onDateChange: (v) {
               formKey.currentState?.save();
               purchaseQualificationsFile.issuingdate = v;
               setState(() {});
            },
            value: purchaseQualificationsFile.issuingdate,
            onSaved: (v) {
              purchaseQualificationsFile.issuingdate = v;
             },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelectDate(
            context,
            label: '有效截止日期',
            firstDate: isNotBlank(purchaseQualificationsFile.issuingdate)
                 ? format.parse(purchaseQualificationsFile.issuingdate!)
                 : null,
            onDateChange: (v) {
               formKey.currentState?.save();
               purchaseQualificationsFile.expirydate = v;
               setState(() {});
            },
            value: purchaseQualificationsFile.expirydate,
            onSaved: (v) {
              purchaseQualificationsFile.expirydate = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInput(
            label: '备注',
            value: purchaseQualificationsFile.remark,
            onSaved: (v) {
              purchaseQualificationsFile.remark = v;
            },
          ),
          Row(
            children: [
              Expanded(flex:4,child: CryInput(
                label: '附件名称',
                enable: false,
                value: purchaseQualificationsFile.filename,
                onSaved: (v) {
                  purchaseQualificationsFile.filename = v;
                },
              ),),
              Expanded(child: IconButton(
                icon: Icon(Icons.upload_rounded),
                onPressed: ()=>_upload(),
              )),
            ],
          )
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            if(isBlank(purchaseQualificationsFile.filename)){
              CryUtils.message("请上传附件");
              return ;
            }
            //打开遮罩
            showDialog(
              context: context,
              builder: (BuildContext context) {
                return LoadingDialog(
                  title: "上传中...",
                  isCancel: false,
                );
              });
            form.save();
            PurchaseQualificationsFileOdooApi.upload(purchaseQualificationsFile.toOdooMap()).then((ResponseBodyApi res) {
              Navigator.pop(context, true);
              if (!res.success!) {
                //CryUtils.message(re s.message!);
                return;
              }
              //关闭遮罩
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              //关闭该窗口
              Navigator.pop(context, true);
              CryUtils.message("上传成功");
            }).onError((error, stackTrace) {
              //关闭遮罩
              Navigator.pop(context, true);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text("企业资质文件上传"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}